import { PageContainer } from '@ant-design/pro-layout';
import { Button, message, Drawer, Spin, Popconfirm, Form, Select, Space } from 'antd';
import { FormattedMessage } from 'umi';
import ProTable from '@ant-design/pro-table';
import ProForm, { DrawerForm, ProFormText, ProFormSelect, ProFormDateRangePicker, ProFormRadio, ProFormTextArea, ModalForm, ProFormUploadDragger } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { PlusOutlined, FileExcelOutlined, UploadOutlined } from '@ant-design/icons';
import { Dealer, TreeData } from '../../../model';
import { Cascader } from 'antd';
import RebateDialog from '../../../components/Common/RebateDialog';
import DealerAuth from '../../../components/Common/DealerAuth';
import { factoryList,dealerListData, areaTwo,updateDealer, saveDealer, deleteDealer, exportDealer, updateStatus, signingView, signSubmit,expiredDealerList } from '../service';
import { exportFile, manufacturerOption, manufacturerOptionArray } from '@/utils/utils';
import { Modal } from 'antd';
import { Table } from 'antd';
import MyDealerInfo from '@/components/Common/MyDealerInfo';
import { Upload } from 'antd';
import request from '@/utils/request';
const { Option } = Select;
const {
  confirm
} = Modal;
export default (() => {
  async function requestAreas() {
    var val = await areaTwo();
    setAreas(val.data);
  }

  async function requestFactory() {
      var param = {}
      var val = await factoryList(param);
      var data = val.data.map((item:any)=>{return {label:item.shortName,value:item.id}})
      setFactoryData(data)
  }

  React.useEffect(() => {
    requestAreas();
    requestFactory();
    return function cleanup() {};
  }, []);
  const errorColumn = [{
    title: '错误行',
    dataIndex: 'rownum'
  }, {
    title: '错误信息',
    dataIndex: 'errerMsg'
  }];

  const access: string = (sessionStorage.getItem('access') as string);
  const actionRef = useRef<ActionType>();

  const [showCreate, setShowCreate] = useState(false);
  const [showUpdate, setShowUpdate] = useState(false);
  const [showAuth, setShowAuth] = useState(false);
  const [rebateModalVisible, setRebateModalVisible] = useState(false);
  const [areas, setAreas] = useState<TreeData[]>();
  const [simpleDeal, setSimpleDeal] = useState({});
  const [spinningFlag, setSpinningFlag] = useState(false);
  const [currentDealerId, setCurrentDealerId] = useState('');
  const [showSign, setShowSign] = useState(false);

  const [fileInfo,setFileInfo] = useState<any>({});
  const [currentLevel, setCurrentLevel] = useState('');
  const [showImport, setShowImport] = useState<boolean>(false);
  const [errorVisible, setErrorVisible] = useState<boolean>(false);
  const [errInfo, setErrInfo] = useState<any[]>([]);
  const [dealerInfo, setDealerInfo] = useState<any>(undefined);
  const [mGenType, setGenType] = useState(1);
  const createRef = useRef<any>();
  const [signDataFlag, setSignDataFlag] = useState(false);
  const [signFileList, setSignFileList] = useState([]);
  const [signData, setSignData] = useState<any>(undefined);
  const [factoryData,setFactoryData] = useState([]);

  const [dealerData,setDealerData] = useState<any[]>([
    {
      loginName:'JXS1021',
      cnName:'北京XXXX有限公司',
      level:'一级',
      priceLevel:'1',
      create_time:'2023-09-01',
      provinces_label:'北京市',
      city_label:'朝阳区',
      status:'1',
      mail:'test@test.com'
    },
    {
      loginName:'JXS1022',
      cnName:'上海XXXX有限公司',
      level:'一级',
      status:'2',
      priceLevel:'1',
      create_time:'2023-09-01',
      provinces_label:'上海市',
      city_label:'奉贤区',
      mail:'test2@test.com'
    },
    {
      loginName:'JXS1025',
      cnName:'南京XXXX有限公司',
      level:'一级',
      priceLevel:'1',
      create_time:'2023-09-01',
      provinces_label:'北京市',
      city_label:'朝阳区',
      status:'1',
      mail:'test3@test.com'
    },
    {
      loginName:'JXS1029',
      cnName:'广州XXXX有限公司',
      level:'一级',
      status:'2',
      priceLevel:'1',
      create_time:'2023-09-01',
      provinces_label:'上海市',
      city_label:'奉贤区',
      mail:'test5@test.com'
    }
  ]);
  const uploadProps = {
    multiple: false,
    name: 'file',
    accept: 'image/*,application/pdf',
    action: '/xwyl/attachment/uploadAttach',
    headers: {
      authorization: 'authorization-text'
    },
    beforeUpload: (file: any, FileList: any[]) => {
      var flag = file.type.indexOf('image/') >= 0 || file.type.indexOf('pdf') >= 0;

      if (!flag) {
        message.error('请上传图片格式或pdf格式');
      }

      return flag;
    }
  };

  const handlePreview = (file: any) => {
    window.open(file.url);
  };

  const handleDelete = async (id: string) => {
    var val = await deleteDealer({
      ids: id
    });

    if (val.errorCode === '200') {
      actionRef.current?.reloadAndRest?.();
    } else {
      message.error('注销失败');
    }
  };

  const resume = async (id: string, status: string) => {
    var val = await updateStatus({
      dealerId: id,
      status: status
    });

    if (val.errorCode === '200') {
      actionRef.current?.reloadAndRest?.();
    } else {
      message.error('注销失败');
    }
  };

  const signImage = async (dealerId: string, value: number) => {
    var param: any = {
      shipId: dealerId + '_sign_' + value
    };
    var data = request('/xwyl/attachment/attachListData', {
      method: 'POST',
      requestType: 'form',
      data: { ...param
      }
    });
    var val = await data;

    if (val.errorCode = 200) {
      val.data.forEach((element: any) => {
        element.uid = element.id;
        element.name = element.attName;
        element.url = element.attPath;
        element.status = 'done';
      }); // if(value==1){
      //   setXwFileList(val.data)
      // }else{
      //   setWmFileList(val.data)
      // }

      setSignFileList(val.data);
    }
  }; //表头信息以及表值设置

  const signColumn: ProColumns[] = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    width: 100,
    valueEnum: manufacturerOption()
  }, {
    title: '起始日期',
    width: 120,
    dataIndex: 'startDate',
    hideInSearch: true
  }, {
    title: '截止日期',
    width: 120,
    dataIndex: 'endDate',
    hideInSearch: true
  }, {
    title: '签约状态',
    width: 120,
    dataIndex: '  ',
    hideInSearch: true,
    renderText: (text) => {
      if (text === 0) {
        return '未签约';
      } else if (text === 1) {
        return '已签约';
      } else if (text === 2) {
        return '已终止';
      }
    }
  }, {
    title: '备注',
    dataIndex: 'bak',
    ellipsis: true,
    hideInSearch: true
  }, {
    title: '操作',
    valueType: 'option',
    render: (text, record: any, _, action) => <a key='editable' onClick={async () => {
      signImage(record.dealerId, record.manufacturer);
      setSignDataFlag(true);
      record.signDate = [record.startDate, record.endDate];
      setSignData(record);
    }}>
          详情
        </a>
  }]; //表头信息以及表值设置

  const columns: ProColumns<Dealer>[] = [{
    title: '经销商代码',
    dataIndex: 'loginName',
    fixed:'left',
    width: 100
  }, {
    title: '经销商名称',
    dataIndex: 'cnName',
    ellipsis:true,
    fixed:'left',
    width: 150,
  }, {
    title: '允许下单',
    dataIndex: 'isOrder',
    hideInSearch:true,
    width: 100,
    renderText:(info:string,record:any)=>{
      if(record.level=='二级'){
        return '否'
      }
      if(info==='0'){
        return '否'
      }
      return '是'
    }
  }
  ,{
    title: '允许下单',
    dataIndex: 'isOrder',
    width: 100,
    valueType:'select',
    valueEnum:{
      "1":{text:'是'},
      '0':{text:'否'}
    },
    editable:false,
   hideInTable:true
  }, {
    title: '状态',
    dataIndex: 'status',
    valueType: 'select',
    width: 100,
    valueEnum: {
      1: {
        text: '激活'
      },
      0: {
        text: '未激活'
      },
      10: {
        text: '已注销'
      }
    },
    renderText: val => {
      if (val == 1) {
        return '激活';
      }

      if (val == 10) {
        return '已注销';
      }

      return '未激活';
    }
  }, {
    title: '等级',
    dataIndex: 'level',
    width: 100,
    valueType: 'select',
    valueEnum: {
      一级: {
        text: '一级'
      },
      二级: {
        text: '二级'
      }
    }
  },{
    title: '价格体系',
    width: 100,
    dataIndex: 'priceLevel',
    valueType: 'select',
    valueEnum: {
      1: {
        text: 'A级'
      },
      2: {
        text: 'B级'
      },
      4: {
        text: 'B-H2级'
      },
      5: {
        text: 'A-H2级'
      },
      6: {
        text: 'C-H2级'
      },
      3: {
        text: '自定义'
      }
    },
    hideInSearch: true
  }, {
    title: '创建时间',
    dataIndex: 'create_time',
    valueType: 'date',
    width: 100,
    hideInSearch: true
  }, {
    title: '激活时间',
    width: 100,
    dataIndex: 'activate_time',
    valueType: 'date',
    hideInSearch: true
  }, {
    title: '注销时间',
    width: 100,
    valueType: 'date',
    dataIndex: 'cancellation_date',
    hideInSearch: true
  }, {
    title: '地区',
    dataIndex: 'office_address',
    valueType: 'select',
    ellipsis:true,
    width: 150,
    hideInSearch: true,
    renderText: (_, record: Dealer) => {
      return `${record.provinces_label}/${record.city_label}`;
    }
  }, {
    title: '邮箱',
    width: 140,
    dataIndex: 'mail',
    ellipsis: true
  },
  //  {
  //   title: '返利余额',
  //   dataIndex: 'amount',
  //   valueType: 'money',
  //   width: 60,
  //   hideInSearch: true
  // },
   {
    title: '操作',
    valueType: 'option',
    fixed: 'right',
    hideInTable: access === 'admin2',
    width: 120,
    render: (text, record: any, _, action) => {
      var array: any = [];
      array.push(<a key='editable' onClick={async () => {
        setDealerInfo(record.id);
        setShowUpdate(true);
      }} >
          基础信息
        </a>);

      if (access != 'financial') {

        array.push(<a key='11' onClick={() => {
          setSimpleDeal({
            dealId: record.id,
            level: record.level,
            'name': record.cnName
          });
          setShowAuth(true);
        }} >
            授权
          </a>);
      }

      return array;
    }
  }];

  function onChange(value: any) {
    console.log(value);
  }

  const onFileUpload = (info: any) => {
    if (info.file.status !== 'uploading') {}

    if (info.file.status === 'done') {
      if (info.file.response.errorCode === '200') {
        message.success(`${info.file.name} 上传成功，后台正在处理...`);
        actionRef.current?.reloadAndRest?.();
        setShowImport(false);
      } else {
        message.error('上传失败: ' + info.file.response.msg);
        setErrorVisible(true);
        setErrInfo(info.file.response.data);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败！`);
    }
  };

  const handleCancel = () => {
    setErrorVisible(false);
    setErrInfo([]);
  };

  const selectUpdateDealer = async (flag:string,ids:any)=>{
    
    var params: any = {
      isTwoInvoicePolicy:flag,
      ids:  ids
    };
    var val = await request('/xwyl/dealer/setIsTwoInvoicePolicy', {
        method: 'POST',
        headers:{
          'Content-Type': 'application/json',
          'authorization':`${sessionStorage.getItem('token')}`
        },
        data: {
          ...params,
        },
    });
    if (val.errorCode = 200) {
      message.success('设置成功')
      actionRef.current?.reloadAndRest?.()
    }else{
      message.error(val.errorMessage)
    }
  }

  const updateTicket =async (flag:string,ids:any)=>{
    var param: any = {
      isOrder:flag,
      ids:  ids.join(',')
    };
    var data = request('/xwyl/dealer/updateDealerIsOrder', {
      method: 'POST',
      requestType: 'form',
      data: { ...param
      }
    });
    var val = await data;
    if (val.errorCode = 200) {
      message.success('设置成功')
      actionRef.current?.reloadAndRest?.()
    }else{
      message.error(val.errorMessage)
    }
  }

  return <PageContainer>
    <ProTable<Dealer> actionRef={actionRef} scroll={{
      x: 1300
    }} 
    dataSource={dealerData}
    headerTitle='经销商列表' columns={columns} rowKey='id' pagination={{
      pageSizeOptions: ['20', '100', '500']
    }} toolBarRender={() => access != 'sale' ? [<Button  type='primary' key='primary' hidden={access === 'admin2'} onClick={() => {
      setCurrentLevel('');
      setGenType(1);
      setShowCreate(true);
    }}>
          <PlusOutlined/> <FormattedMessage id='pages.searchTable.new' defaultMessage='新建'/>
        </Button>] : []} toolbar={{
      settings: []
    }} search={{
      span: 5
    }} 
    />

         <DrawerForm title='经销商新增' onVisibleChange={setShowCreate} visible={showCreate} drawerProps={{
      destroyOnClose: true,
      forceRender: true
    }} formRef={createRef} onFinish={async (values: any) => {
      values.provinces = values.areas[0];

      if (values.areas.length > 1) {
        //TODO 后续调整
        values.city = values.areas[1];
      }

      if (currentLevel != '二级') {
        values.generateType = '2';
      } else {
        if (mGenType == 1) {
          if (!values.primary_contact || values.primary_contact === '') {
            message.error('请输入联系人');
            return false;
          }

          if (!values.primary_phone || values.primary_phone === '') {
            message.error('请输入联系电话');
            return false;
          } // if(!values.address||values.address===''){
          //   message.error(请输入详细地址);
          //   return false;
          // }

        }
      }

      var val = await saveDealer(values);

      if (val.errorCode === '200') {
        message.success('提交成功');
        actionRef.current?.reloadAndRest?.();
        return true;
      } else {
        message.error(val.msg);
        return false;
      }
    }} >
           <ProForm.Group>
            <ProFormText name='CnName' label='经销商名称(中文)' placeholder='请输入经销商中文名称' width='md' rules={[{
          required: true
        }]}/>
            <ProFormText name='EnName' label='关联经销商名称' placeholder='请输入关联经销商名称' width='md' />
          </ProForm.Group>
          <ProForm.Group>
              <Form.Item
                  name="factoryIds"
                  rules={[{
                    required: true,
                  }]}
                  label="授权厂家"
                  style={{width:'440px'}}
                >
                  <Select  mode="multiple"
                    style={{ width: '100%' }}
                    allowClear>
                      {factoryData.map((item:any)=>{
                        return <Option value={item.value} key={item.value}>{item.label}</Option>
                      })}
                    </Select>
              </Form.Item>
          </ProForm.Group>
          <ProForm.Group >
              <Form.Item style={{
          width: 330
        }} name='areas' label='省/市' rules={[{
          required: true
        }]} >
                <Cascader changeOnSelect options={areas} placeholder='请选择' onChange={onChange} />
              </Form.Item>
              <ProFormText name='mail' label='邮箱' placeholder='请输入邮编' width='md' rules={[{
          required: true
        }, {
          pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
          message: '邮箱格式不正确'
        }]} />
          </ProForm.Group>
          <ProForm.Group>
              <ProFormSelect name='level' allowClear={false} label='经销商等级' placeholder='请选择经销商等级' width='md' rules={[{
          required: true
        }]} options={[{
          value: '一级',
          label: '一级'
        }, {
          value: '二级',
          label: '二级'
        }]} fieldProps={{
          onSelect: v => {
            setCurrentLevel(v);
          }
        }}/>
          </ProForm.Group>
          <ProForm.Group >
          <ProFormSelect name='isTwoInvoicePolicy' allowClear={false} label='两票制' placeholder='请选择是否是两票制' width='md' rules={[{
          required: true
        }]} options={[{
          value: '0',
          label: '否'
        }, {
          value: '1',
          label: '是'
        }]}/>
            <ProFormRadio.Group hidden={currentLevel != '二级'} name='generateType' label='是否生成商业经销商' initialValue={mGenType} fieldProps={{
          onChange: e => {
            setGenType(e.target.value);
            createRef?.current?.setFieldsValue({
              generateType: e.target.value
            });
          }
        }} options={[{
          label: '是',
          value: 1
        }, {
          label: '否',
          value: 2
        }]}/>
          </ProForm.Group>
          <div hidden={mGenType == 2} >
              <div hidden={currentLevel != '二级'} ><span style={{
            color: 'red'
          }} >*</span>联系人姓名</div>
              <ProFormText hidden={currentLevel != '二级'} name='primary_contact' label='' placeholder='请输入联系人姓名'  />
              <div hidden={currentLevel != '二级'} ><span style={{
            color: 'red'
          }} >*</span>联系电话</div>
              <ProFormText hidden={currentLevel != '二级'} name='primary_phone' label='' placeholder='请输入联系电话'  />
              <div hidden={currentLevel != '二级'} ><span style={{
            color: 'red'
          }} >*</span>详细地址</div>
              <ProFormText hidden={currentLevel != '二级'} name='address' label='' placeholder='请输入详细地址' width='xl'  />
            </div>
         </DrawerForm>
         <Drawer title={'详情'} width={1000} destroyOnClose={true} visible={showUpdate} onClose={() => setShowUpdate(false)} >
              <MyDealerInfo admin={true} state={true} dealerId={dealerInfo} finishCallback={() => {
        setShowUpdate(false);
      }}></MyDealerInfo>
         </Drawer>
         <RebateDialog onCancel={() => {
      setRebateModalVisible(false);
    }} modalVisible={rebateModalVisible} dealerId={currentDealerId} />
         <Drawer title={'授权'} width={1100} visible={showAuth} destroyOnClose={true} onClose={() => {
      setShowAuth(false);
    }} >
           <DealerAuth data={simpleDeal} callback={(showFlag:any) => {
        actionRef.current?.reloadAndRest?.();

        if (!showFlag) {
          setShowAuth(false);
        }
      }} />
         </Drawer>
         
         <Drawer title={'经销商签约'} width={1000} style={{
      zIndex: 50
    }} forceRender={true} visible={showSign} destroyOnClose={true} onClose={() => {
      setShowSign(false);
    }} >
           <ProTable columns={signColumn} rowKey='id' request={async (params: any, sorter, filter) => {
        params.dealerId = dealerInfo;
        var data = signingView({ ...params,
          filter
        });
        return data;
      }} pagination={{
        pageSizeOptions: ['20', '100', '500']
      }} toolBarRender={() => [<Button type='primary' key='primary' onClick={() => {
        setSignDataFlag(true);
        setSignData({
          manufacturer: 1
        });
      }}>
                <PlusOutlined/> <FormattedMessage id='pages.searchTable.new' defaultMessage='新建'/>
              </Button>]} toolbar={{
        settings: []
      }} />
         </Drawer>



        

      <ModalForm title={fileInfo.name} onVisibleChange={v => {
      setShowImport(v);
    }} modalProps={{
      destroyOnClose: true,
      forceRender: true
    }} visible={showImport} onFinish={async (values: any) => {
      console.log(values);
      return true;
    }} >
             <div style={{
        margin: '10px 0 20px 0'
      }} ><a href={fileInfo.templateUrl} download={fileInfo.templateName}><Button type='primary' > <FileExcelOutlined />{fileInfo.btn}</Button></a></div>
            <ProFormUploadDragger label='选择excel上传' name='file' action={fileInfo.action} fieldProps={{
        name: 'file',
        headers: {
          'authorization': (sessionStorage.getItem('token') as string)
        }
      }} max={1} onChange={onFileUpload} />
       </ModalForm>


         <Modal visible={errorVisible} title='导入错误提示' width={800} footer={null} destroyOnClose={true} onCancel={handleCancel}>
          <Table dataSource={errInfo} style={{
        height: 400
      }} columns={errorColumn} pagination={false} rowKey='rownum' ></Table>
        </Modal>
        <DrawerForm style={{
      zIndex: 100
    }} width={1000} title='详情' onVisibleChange={setSignDataFlag} visible={signDataFlag} drawerProps={{
      destroyOnClose: true,
      forceRender: true
    }} onFinish={async (values: any) => {
      var param = {};

      if (signData.id) {
        param = {
          id: signData.id,
          dealerId: signData.dealerId,
          manufacturer: signData.manufacturer,
          signState: values.signState,
          bak: values.bak,
          endDate: values.signDate[1],
          startDate: values.signDate[0]
        };
      } else {
        param = {
          dealerId: dealerInfo,
          manufacturer: signData.manufacturer,
          signState: values.signState,
          bak: values.bak,
          endDate: values.signDate[1],
          startDate: values.signDate[0]
        };
      }

      var val = await signSubmit(param);

      if (val.errorCode === '200') {
        setShowSign(false);
        message.success('提交成功');
        return true;
      } else {
        message.error('提交失败');
        return false;
      }
    }}>
                <ProFormSelect name='manufacturer' fieldProps={{
        onSelect: value => {
          var data = { ...signData
          };
          data.manufacturer = value;
          setSignData(data);
        }
      }} hidden={signData?.id} rules={[{
        required: true
      }]} label='厂家' options={manufacturerOptionArray()} initialValue={signData?.manufacturer} allowClear={false} placeholder='请选择' />
                  <ProFormDateRangePicker name='signDate' rules={[{
        required: true
      }]} label='签约期限' initialValue={signData?.signDate} ></ProFormDateRangePicker>
                  <ProFormRadio.Group name='signState' label='签约状态' rules={[{
        required: true
      }]} initialValue={signData?.signState} options={[{
        label: '已签约',
        value: 1
      }, {
        label: '未签约',
        value: 0
      }, {
        label: '已终止',
        value: 2
      }]}  />
                  <ProFormTextArea name="bak" placeholder='请输入' initialValue={signData?.bak} label='签约备注' fieldProps={{
        showCount: true,
        maxLength: 200
      }}/>
                    <Upload {...uploadProps} onPreview={handlePreview} fileList={signFileList} onRemove={record => {
        confirm({
          content: '确定删除吗？',
          onOk: async () => {
            var req = request('/xwyl/attachment/deleteAtt', {
              method: 'POST',
              requestType: 'form',
              data: { ...{
                  id: record.uid
                },
                method: 'post'
              }
            });
            var val = await req;

            if (val.errorCode === '200') {
              var tempList = signFileList;
              var newList = tempList.filter((item: any) => {
                return item.uid != record.uid;
              });
              setSignFileList(newList);
              message.success('删除成功');
            } else {
              message.error('删除失败');
            }
          },

          onCancel() {
            console.log('Cancel');
          }

        });
      }} onChange={(info: any) => {
        if (info.file.status === 'done') {
          if (info.file.response.errorCode === '200') {
            var list: any = signFileList;
            list = [...list];
            message.success(`${info.file.name}上传成功`);
            var data = info.file.response.data;
            data.uid = data.attId;
            data.name = info.file.name;
            data.url = data.location;
            data.status = 'done';
            list.push(data);
            setSignFileList(list);
          } else {
            message.error(`${info.file.name} 上传失败.`);
          }
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败.`);
        }
      }} data={{
        'shipId': dealerInfo + '_sign_' + signData?.manufacturer,
        'userId': sessionStorage.getItem('userId')
      }} headers={{
        'authorization': `${sessionStorage.getItem('token')}`
      }} >
                      <Button icon={<UploadOutlined/>} ><span style={{
            color: 'red'
          }}>*</span>上传合同附件</Button>
                  </Upload>
         </DrawerForm>
    <Spin spinning={spinningFlag} style={{
      transform: 'translate(-50%,-50%)',
      left: '50%',
      top: '50%',
      position: 'absolute'
    }} />
  </PageContainer>;
});